<?php
namespace App\HttpController;

use App\HttpController\UserBase;
use App\Models\UserModel;
use App\Models\Project;
use App\Models\Assign;
use EasySwoole\EasySwoole\Config;
use App\Models\File;
use EasySwoole\Http\Message\Status;
use EasySwoole\HttpAnnotation\AnnotationTag\Param;
use EasySwoole\Component\Di;
class Auth extends UserBase
{
    protected $whiteList = ['login', 'register','getloginuser','artlist'];

    public function login()
    {
        // $param = $this->request()->getRequestParam();
        // var_dump($param);


        $content = $this->request()->getBody()->__toString();
        $param = json_decode($content, true);

var_dump($param);
        $model = new UserModel();
        $model->userAccount = $param['userAccount'];
        $model->userPassword = md5($param['userPassword']);

        if ($userInfo = $model->login()) {
            $sessionHash = md5(time() . $userInfo->userId);
           $redisu = \EasySwoole\Pool\Manager::getInstance()->get('redis')->getObj();
            //write userinfo to redis
            $redisu->set(sprintf("logintoken-%s",$sessionHash),json_encode($userInfo));
            $rs = $userInfo->toArray();
            \EasySwoole\Pool\Manager::getInstance()->get('redis')->recycleObj($redisu);
            unset($rs['userPassword']);
            $rs['userSession'] = $sessionHash;
            $this->response()->setCookie('userSession', $sessionHash, time() + 3600, '/');
            $this->writeJson(Status::CODE_OK, $rs);
        } else {

            $this->writeJson(Status::CODE_OK, 'errpwd');
        }
    }


    public function logout()
    {
 
        $sessionKey = $this->request()->getCookieParams('userSession');
   
        if (empty($sessionKey)) {
            $this->writeJson(Status::CODE_UNAUTHORIZED, '', '尚未登入');
            return false;
        }
        $redis=\EasySwoole\Pool\Manager::getInstance()->get('redis')->getObj();
        
         $result =  $redis->del(sprintf("logintoken-%s",$sessionKey));
         var_dump($result);
         \EasySwoole\Pool\Manager::getInstance()->get('redis')->recycleObj($redis);

        if ($result) {
            $this->writeJson(Status::CODE_OK, '', "登出成功");
        } else {
            $this->writeJson(Status::CODE_UNAUTHORIZED, '', 'fail');
        }
    }


   public function getloginuser(){
        $userinfo = $this->getWho();
        if ($userinfo == null) {
            $this->writeJson(Status::CODE_OK,'','CODE_UNAUTHORIZED');
        }else{

        $this->writeJson(Status::CODE_OK,$userinfo);
   }
    }



    function getdetailfiles(){

    $id = $this->input("id");

    $list = File::create()->all(['itemid'=>intval($id)]);

    var_dump($list);

    $this->writeJson(200,$list);


   }






    public function artlist()
    {
        $page = $this->input('page',1);
        $limit =   \EasySwoole\EasySwoole\Config::getInstance()->getConf('pagelimit');;    
        $model = \App\Models\Article::create()->limit($limit * ($page - 1), $limit)->withTotalCount();
        $list = $model->order("id",'DESC')->all(null);
        $result = $model->lastQueryResult();
        $total = $result->getTotalCount();
        $pagecon = $this->showPageStringAsAJAX("jumpage",$page,$limit,$total);
        $this->writeJson(200,['list'=>$list,'res'=>$result,'total'=>$total,'pg'=>$pagecon]);

    }



    public function showPageStringAsAJAX( $jumpFun, $currentPage, $pageSize, $totalCount){
                 $pageSize = $pageSize == 0 ? 3 : $pageSize;
                 $totalPages = floor(($totalCount + $pageSize - 1) / $pageSize); //总页数
                $output = "";
               if ($totalPages > 1)
                {
                    {//处理首页连接
                        $output .= "<a class='pages-a' href='javascript:void(0);'  onclick='".$jumpFun."(1,".$pageSize.")'>首页</a>";
                
                    }
                    if ($currentPage > 1)
                   {//处理上一页的连接
                        $output .= "<a class='pages-a' href='javascript:void(0);' onclick='".$jumpFun."(".($currentPage - 1).", ".$pageSize.")'>上一页</a>";
                    }
                   else
                    {
                        // output.Append("<span class='pageLink'>上一页</span>");
                    }
                
                    $output .= " ";
                    $currint = 5;
                    for ($i = 0; $i <= 10; $i++)
                 {//一共最多显示10个页码，前面5个，后面5个
                        if (($currentPage + $i - $currint) >= 1 && ($currentPage + $i - $currint) <= $totalPages)
                        {
                            if ($currint == $i)
                            {//当前页处理
       
                                $output .= "<a class='pages-a on'  href='javascript:void(0);'>$currentPage</a>";
                            }
                           else
                            {//一般页处理
                                $output .= "<a  class='pages-a' href='javascript:void(0);' onclick='".$jumpFun."(".($currentPage + $i - $currint).",".$pageSize.")'>".($currentPage + $i - $currint)."</a>";
                            }
                        }
                        $output .= " ";
                    }
                    if ($currentPage < $totalPages)
                    {//处理下一页的链接
                        $output .= "<a  class='pages-a' href='javascript:void(0);' onclick='".$jumpFun."(".($currentPage + 1).",".$pageSize.")'>下一页</a>";
                    }
                    else
                 {
                     //output.Append("<span class='pageLink'>下一页</span>");
                    }
                    $output .=" ";
                    if ($currentPage != $totalPages)
                    {
                        //处理末页的链接
                        $output .= "><a  href='javascript:void(0);' class='pages-a' onclick='".$jumpFun."(".$totalPages.", ".$pageSize.")'>末页</a>";
                    }
                    
              }
                //$output .= "第".$currentPage."页 / 共".$totalPages."页";//这个统计加不加都行
                
                return $output;
            }









            function getassign(){
                $id = $this->input("itemid");
                $item = Project::create()->where(['id'=>intval($id)])->get();
                $assigns = Assign::create()->where(['itemid'=>intval($id)])
                ->join("user_list","user_list.id=assign.assign_eid")->field(["assign.*",
                "user_list.phone","user_list.good"])->all();
                $isjg=true;
                $group_assign = [];
                for($i=0;$i<count($assigns);$i++){
                    $assigns[$i]['isexpired'] = $assigns[$i]['uuid'] == $item['approveuuid'] ? "已激活":"已失效";
                   
                }

                if($item['cash'] > Config::getInstance()->getConf('CASH_TRIGGER')){

                    $isjg = false;

                }

                $this->writeJson(200,['code'=>200,'isjg'=>$isjg,'assign'=>$assigns]);
            }






    public function readart()
    {
        $id = $this->input('id');
        $info = \App\Models\Article::create()->get(['id'=>intval($id)]);
        $img = \App\Models\Fileart::create()->all(['articleid'=>intval($id)]);
  
        \App\Models\Article::create()->update(['viewnumber'=>($info['viewnumber']+1)],['id'=>intval($id)]);
        $this->writeJson(200,['info'=>$info,'img'=>$img]);
    }




    function editpwd(){
        $user = $this->who;
        $pwd = Usermodel::create()->where(['id'=>$user['id']])->get();
        var_dump($pwd);

        $old = $this->input("old");
        $new = $this->input("new");
var_dump($old);
        if(md5($old) != $pwd['userPassword']){

            $this->writeJson(200,['code'=>500,'msg'=>'原密码不正确']);
            return false;
        }


        $res = UserModel::create()->update(['userPassword'=>md5($new)],['id'=>$user['id']]);

        if($res){

            $this->writeJson(200,['code'=>200,'msg'=>'修改成功']);
        }



    }


    function getuser(){
        $id = $this->input("id");

        $this->writeJson(200,['user'=>UserModel::create()->get(['id'=>intval($id)])]);


    }
    function getdetail(){
        $params = $this->request()->getRequestParam();
        $id = $params['id'];
        if (!$id) {
            $this->writeJson(404,"NOT FOUND ITEM");
        }
        $project = Project::create()->get(["id"=>intval($id)]);
        $this->writeJson(200,['item'=>$project]);
    }





}
















